package cn.dslcode.security.config.oauth2.resourceserver;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dongsilin
 * @version 2018/6/8.
 */
public class UserResourceServerConfigurer implements ResourceServerConfigurer {

    private String resourceId;
    private TokenStore tokenStore;

    public UserResourceServerConfigurer(String resourceId, TokenStore tokenStore) {
        this.resourceId = resourceId;
        this.tokenStore = tokenStore;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        Assert.notNull(resourceId, "resourceId is not null");
        Assert.notNull(tokenStore, "tokenStore is not null");
        resources.resourceId(resourceId).tokenStore(tokenStore).stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER)
            .and()
            .requestMatchers().antMatchers("/user/**")
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/user/**").access("#oauth2.hasScope('read')")
            .antMatchers(HttpMethod.POST, "/user/**").access("#oauth2.hasScope('write')")
            .antMatchers(HttpMethod.PATCH, "/user/**").access("#oauth2.hasScope('write')")
            .antMatchers(HttpMethod.PUT, "/user/**").access("#oauth2.hasScope('write')")
            .antMatchers(HttpMethod.DELETE, "/user/**").access("#oauth2.hasScope('write')")
            .and()
            .headers().addHeaderWriter((HttpServletRequest request, HttpServletResponse response) -> {
            response.addHeader("Access-Control-Allow-Origin", "*");
            if (request.getMethod().equals("OPTIONS")) {
                response.setHeader("Access-Control-Allow-Methods", request.getHeader("Access-Control-Request-Method"));
                response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
            }
        });
    }


}
